<?php
/**
 *  
 * ds
 * 2020.08.13
 */
namespace App\Models\MainDB;

use App\Enums\MallEnum;
use Illuminate\Database\Eloquent\Model;

class MallCategories extends Model{

    protected $table = 'ln_mall_categories';     //数据库内完整表名

    protected $primaryKey = 'id';    //主键名

    protected $fillable = [
        'id',      //  
        'title',         //   
        'add_time',         //    
        'parent_id',         //父分类id
        'icon',         //图标
        'sort',         //排序号，降序
        'is_show',         //是否显示：1：是；0：否
    ];

    public $timestamps = false;

    //获取所有单品的分类
    public function getSubCate($topCateId)
    {
        switch ($topCateId) {
            case MallEnum::PRODUCT_CATE_ID_SUIT:
                $where = ['is_join_suit' => 1];
                break;
            case MallEnum::PRODUCT_CATE_ID_DISCOUNT:
                $where = ['is_join_discount' => 1];
                break;
            case MallEnum::PRODUCT_CATE_ID_ACTIVITY:
                $where = ['is_join_activity' => 1];
                break;
            case MallEnum::PRODUCT_CATE_ID_RARITY:
                $where = ['is_join_rarity' => 1];
                break;
            default:
                $where = [];
        }

        $cates = $this->select('id', 'title')
            ->where($where)
            ->where('parent_id', MallEnum::PRODUCT_CATE_ID_ALL)
            ->get()->toArray();
        return array_column($cates, null, 'id');
    }

    //递归查询某分类的所有子分类id
    public function getAllSubCateId($cateId)
    {
        static $cateIdArr = [];
        $subCateIds = $this->where('parent_id', $cateId)->pluck('id');
        if (empty($subCateIds)) return;
        foreach ($subCateIds as $subCateId) {
            $cateIdArr[] = $subCateId;
            $this->getAllSubCateId($subCateId);
        }
        return $cateIdArr;
    }

    public function getCategories($where = [])
    {
        return app('model_mall_categories')
            ->select('id', 'title', 'icon', 'is_show', 'sort')
            ->where('new_parent_id', 0)
            ->where($where)
            ->orderBy('new_sort', 'asc')
            ->get()->toArray();
    }
}